package com.ruoyi.project.app.service;

import com.ruoyi.project.app.response.WordByTypeResponse;
import com.ruoyi.project.system.word.mapper.WordMapper;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.StringWriter;
import java.util.Date;
import java.util.Map;

@Service
@SuppressWarnings("ALL")
public class AppWordService {
    @Autowired
    private WordMapper mapper;

    /**
     * 通过类型获取文档
     *
     * @param type 类型
     * @return 文档
     */
    public Object wordByType(Map<String, Object> params) {
        WordByTypeResponse response = mapper.wordByType(params);
        Date date = new Date();
        params.put("systemCurrentTime", date);
        if (response != null) response.setHtml(resolverFreemarkerTemplate(response.getHtml(), params));
        return response;
    }

    /**
     * 解析模版
     *
     * @param src 模板
     * @param map 数据
     * @return
     */
    private String resolverFreemarkerTemplate(String src, Map<String, Object> map) {
        if (src != null && !"".equals(src)) {
            StringWriter writer = null;
            try {
                writer = new StringWriter();
                //创建一个模版对象
                Template template = new Template(null, src, null);
                //空值处理
                template.setClassicCompatible(true);
                template.setEncoding("UTF-8");
                //合并数据模型与模板
                template.process(map, writer);
                return writer.toString();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (writer != null) writer.flush();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    if (writer != null) writer.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
